package com.library.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.library.vo.ResultVO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * JWT认证入口点
 *
 * @author Library Team
 */
@Slf4j
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        // 设置响应类型和编码
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        // 返回错误信息
        ResultVO<Object> resultVO = ResultVO.error(401, "未授权，请先登录");

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResult = objectMapper.writeValueAsString(resultVO);

        response.getWriter().write(jsonResult);

        log.warn("未授权访问被拒绝 - URI: {}, 原因: {}", request.getRequestURI(), authException.getMessage());
    }

}
